import re
from typing import List, Dict
from src.comment import extract_name_and_desc

DEFAULT_DATA = {
    "status": 0,
    "parent_id": None,
}


def parse(file_path: str, app_name: str) -> List[Dict]:
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read()

    # 获取类名和命名空间
    class_match = re.search(r"class\s+(\w+)", content)
    if not class_match:
        return []

    class_name = class_match.group(1)
    namespace_match = re.search(r"namespace\s+(.+?);", content)
    namespace = namespace_match.group(1) if namespace_match else ""

    # 获取所有公共方法
    method_matches = re.finditer(r"public\s+function\s+(\w+)", content)

    permissions = []

    # 应用级权限
    permissions.append(
        {
            "name": app_name,
            "code": app_name.lower(),
            "description": f"应用权限 {app_name}",
            "app": app_name,
            "parent_id": None,
            "status": 0,  # 启用
            "category": "app",
            "_type": "app",
            "_controller": None,
            "_namespace": None,
            **DEFAULT_DATA
        }
    )

    # 控制器级权限
    controller_code = f"{app_name}:{class_name}"
    permissions.append(
        {
            "name": f"{app_name}.{class_name}",
            "code": controller_code.lower(),
            "description": f"控制器权限 {app_name}.{class_name}",
            "app": app_name,
            "parent_id": None,
            "status": 0,
            "category": "controller",
            "_type": "controller",
            "_parent_code": app_name,  # 父权限code (用于SQL关联)
            "_controller": class_name,
            "_namespace": namespace,
            **DEFAULT_DATA
        }
    )

    # 方法级权限
    for method_match in method_matches:
        method_name = method_match.group(1)

        # 跳过魔术方法
        if method_name.startswith("__"):
            continue

        # 尝试获取函数体内容（从函数声明开始到结束大括号）
        func_start = method_match.start()
        # 查找函数体开始位置
        brace_start = content.find('{', func_start)
        if brace_start == -1:
            continue

        brace_count = 1
        brace_end = brace_start + 1
        n = len(content)

        # 匹配函数体的结束位置（处理嵌套大括号）
        while brace_end < n and brace_count > 0:
            if content[brace_end] == '{':
                brace_count += 1
            elif content[brace_end] == '}':
                brace_count -= 1
            brace_end += 1

        # 提取整个函数体（不含外层大括号）
        function_body = content[brace_start +
                                1:brace_end - 1] if brace_end > brace_start else ''

        # 判断类型：检查函数体中是否包含视图调用关键词
        view_keywords = [
            "View::fetch",
            "return view(",
            "return $this->fetch",
            # "return $this->display",
            # "return fetch(",
            # "return display(",
        ]
        method_type = "method"  # 默认类型为API方法
        for keyword in view_keywords:
            if keyword in function_body:
                method_type = "page"  # 检测到视图调用，标记为页面
                break

        # 提取方法描述
        method_start_index = method_match.end()
        description = extract_name_and_desc(content[:method_start_index])

        permissions.append(
            {
                "name": f"{app_name}.{class_name}.{method_name}",
                "code": f"{app_name}:{class_name}:{method_name}".lower(),
                "description": f"{'页面' if method_type == 'page' else '方法'}权限 " + description,
                "app": app_name,
                "parent_id": None,
                "status": 0,
                "category": method_type,
                "_type": method_type,  # 动态设置类型
                "_parent_code": controller_code,  # 父权限code (用于SQL关联)
                "_controller": class_name,
                "_namespace": namespace,
                **DEFAULT_DATA
            }
        )

    return permissions
